const ResType = {
    Text: 1,
    Image: 2,
    CubeImage: 3,  // 要求一次6张
};

let loader = require('./loader');

class ResItem {
    constructor(filepath, type = ResType.Text) {
        this.filepath = filepath;
        this.type = type;
        this.data = null;
    }

    getKey() {
        if (Array.isArray(this.filepath)) {
            return this.filepath[0];
        } else {
            return this.filepath;
        }
    }

    load(cb) {
        switch (this.type) {
            case ResType.Text:
                loader.loadText(this.filepath).then(content => {
                    this.data = content;
                    cb(true, this.getKey())
                }).catch(() => {
                    cb(false, this.getKey())
                });
                break;
            case ResType.Image:
                loader.loadImage(this.filepath).then(content => {
                    this.data = content;
                    cb(true, this.getKey())
                }).catch(() => {
                    cb(false, this.getKey());
                });
                break;
            case ResType.CubeImage:
                loader.loadCubeImage(this.filepath).then(content => {
                    this.data = content;
                    cb(true, this.getKey());
                }).catch(() => {
                    cb(false, this.getKey());
                });
                break;
        }
    }
}


let resCache = {
    size: 0,
    cache: {},
    addRes(resItem) {
        let key = resItem.getKey();
        if (!this.cache[key]) {
            this.size++;
            this.cache[key] = resItem;
        }
    },

    getRes(key) {
        return this.cache[key];
    },

    load(allloadedcb) {
        let total = this.size;
        let compeleted = 0;
        for (let k in this.cache) {
            this.cache[k].load((ret, key) => {
                if (ret) {
                    compeleted++;
                    if (compeleted >= total) {
                        allloadedcb();
                    }
                } else {
                    console.error(`load key:${key} failed!`);
                }
            });
        }
    }
};


window.onload = function () {

    resCache.addRes(new ResItem('assets/skybox.vs.glsl'));
    resCache.addRes(new ResItem('assets/skybox.fs.glsl'));
    resCache.addRes(new ResItem('assets/cube.obj'));
    resCache.addRes(new ResItem([
        'assets/skybox/+x.png', 'assets/skybox/-x.png',
        'assets/skybox/+y.png', 'assets/skybox/-y.png',
        'assets/skybox/+z.png', 'assets/skybox/-z.png',
    ], ResType.CubeImage));


    resCache.load(() => {
        console.log('-----------------------资源加载完毕.....');

        app.init();

    })
};


let app = {
    init(){},
    loop(){}
};
